package com.landiao.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.landiao.common.Constant;
import com.landiao.common.pojo.PerformanceDetail;
import com.landiao.common.pojo.PerformanceHisInfo;
import com.landiao.common.pojo.Querier;
import com.landiao.common.utils.DateUtil;
import com.landiao.entities.OrderSchedule;
import com.landiao.entities.RoleCommisionRule;
import com.landiao.mapper.OrderScheduleMapper;

/**
 * 功能说明:
 *
 */
@Service
public class OrderScheduleService extends BaseService<OrderSchedule, String> {

	@Autowired
	private SysConfigService sysConfigService;

	@Autowired
	private RoleCommisionRuleService ruleService;

	@Override
	protected OrderScheduleMapper getBaseMapper() {
		// TODO Auto-generated method stub
		return (OrderScheduleMapper)baseMapper;
	}

	public List<OrderSchedule> queryList(OrderSchedule t){
		return this.baseMapper.queryByPage(t, null);
	}

	/**
	 * 获取员工历史业绩(不算商品)
	 * @param querier
	 * @return
	 */
	public List<PerformanceHisInfo> getPerformanceHisByEmployeeId(String compId,String employeeId,Date beginTime,Date endTime,String roleId){
		Querier querier = new Querier();
		querier.set("compId", compId);
		querier.set("employeeId", employeeId);
		querier.set("beginTime", beginTime);
		querier.set("endTime", endTime);
		querier.set("state", "10F");

		BigDecimal vipBalancePercent = new BigDecimal(sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.VIP_BALANCE_PERCENT.toString()).getVal1()).divide(new BigDecimal("100"));
		BigDecimal couponPercent = new BigDecimal(sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.COUPON_PERCENT.toString()).getVal1()).divide(new BigDecimal("100"));
		List<OrderSchedule> list = this.getBaseMapper().selectOrderScheduleNoMdse(querier);
		List<PerformanceHisInfo> hisList = new ArrayList<>();
		Set<String> orderDetailSet = new HashSet<>();
		if(list!=null&&list.size()>0){
			Map<String, PerformanceHisInfo> monthMap = new LinkedHashMap<>();
			for(OrderSchedule sche:list){
				String month = DateUtil.date2Str(sche.getStatedate(), "yyyy年MM月");
				if(monthMap.containsKey(month)){
					PerformanceHisInfo his = monthMap.get(month);
					if(!orderDetailSet.contains(sche.getOrderDetailId())){
						orderDetailSet.add(sche.getOrderDetailId());
						his.setBaseAmount(his.getBaseAmount().add(sche.getBaseAmount()));
					}
					if(sche.getRoleId().equals(Constant.RoleIdEnum.FXS.toString())){
						his.setFxsBaseAmount(his.getFxsBaseAmount().add(sche.getBaseAmount()));
						if(sche.getCommisionAmount()!=null){
							his.setFxsCommisionAmount(his.getFxsCommisionAmount().add(sche.getCommisionAmount()));
						}
					}else{
						if(sche.getCommisionAmount()!=null){
							his.setCommisionAmount(his.getCommisionAmount().add(sche.getCommisionAmount()));
						}
					}
					his.getScheList().add(sche);
				}else{
					orderDetailSet.add(sche.getOrderDetailId());
					PerformanceHisInfo his = new PerformanceHisInfo();
					his.setMonth(month);
					his.setBaseAmount(sche.getBaseAmount());
					if(sche.getRoleId().equals(Constant.RoleIdEnum.FXS.toString())){
						his.setCommisionAmount(new BigDecimal("0"));
						his.setFxsBaseAmount(sche.getBaseAmount());
						his.setFxsCommisionAmount(sche.getCommisionAmount()==null?new BigDecimal("0"):sche.getCommisionAmount());
					}else{
						his.setCommisionAmount(sche.getCommisionAmount()==null?new BigDecimal("0"):sche.getCommisionAmount());
						his.setFxsBaseAmount(new BigDecimal("0"));
						his.setFxsCommisionAmount(new BigDecimal("0"));
					}
					his.setScheList(new ArrayList<OrderSchedule>());
					his.getScheList().add(sche);
					monthMap.put(month, his);
				}
			}

			for (Map.Entry<String, PerformanceHisInfo> entry : monthMap.entrySet()) {
				PerformanceHisInfo his = entry.getValue();
				if(roleId.equals(Constant.RoleIdEnum.FXS.toString())){//发型师
					if(!(his.getFxsCommisionAmount()!=null&&his.getFxsCommisionAmount().doubleValue()!=0)){//已结算
						RoleCommisionRule rule = this.ruleService.getRatio(compId, his.getFxsBaseAmount());
						BigDecimal ruleRatio = rule.getCommisionRatio().divide(new BigDecimal("100"));
						for(OrderSchedule sche:his.getScheList()){
							if(sche.getRoleId().equals(Constant.RoleIdEnum.FXS.toString())){
								BigDecimal amount = sche.getBaseAmount().multiply(ruleRatio);
								if("10A".equals(sche.getIsDk())){
									amount = amount.multiply(couponPercent);
								}
								if("10A".equals(sche.getIsBalance())){
									amount = amount.multiply(vipBalancePercent);
								}
								his.setFxsCommisionAmount(his.getFxsCommisionAmount().add(amount));
							}
						}
					}
				}
				his.setBaseAmount(his.getBaseAmount().setScale(1,BigDecimal.ROUND_HALF_UP));
				his.setCommisionAmount(his.getCommisionAmount().add(his.getFxsCommisionAmount()).setScale(1,BigDecimal.ROUND_HALF_UP));
//				his.setCommisionAmount(his.getCommisionAmount().setScale(1,BigDecimal.ROUND_HALF_UP));
				
				hisList.add(his);
			}  
		}
		return hisList;
	}
	
	/**
	 * 获取员工本日、本月的业绩、提成(不算商品)
	 * @param querier
	 * @return
	 */
	public Map<String,BigDecimal> getPerformanceByEmployeeId(String compId,String employeeId,String roleId){
		Date nowDate = new Date();
		String day = DateUtil.date2Str(nowDate, "yyyyMMdd");
		Querier querier = new Querier();
		querier.set("compId", compId);
		querier.set("employeeId", employeeId);
		querier.set("beginTime", DateUtil.getStartTime(DateUtil.getMonthFirstDate(nowDate, 0)));
		querier.set("endTime", DateUtil.getEndTime(nowDate));
		querier.set("state", "10F");

		BigDecimal vipBalancePercent = new BigDecimal(sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.VIP_BALANCE_PERCENT.toString()).getVal1()).divide(new BigDecimal("100"));
		BigDecimal couponPercent = new BigDecimal(sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.COUPON_PERCENT.toString()).getVal1()).divide(new BigDecimal("100"));
		
		List<OrderSchedule> list = this.getBaseMapper().selectOrderScheduleNoMdse(querier);
		Map<String, BigDecimal> map = new LinkedHashMap<>();
		BigDecimal monthAmount = new BigDecimal("0");
		BigDecimal fxsMonthAmount = new BigDecimal("0");
//		BigDecimal fxsMonthCommisionAmount = new BigDecimal("0");
		BigDecimal monthCommisionAmount = new BigDecimal("0");
		BigDecimal dayAmount = new BigDecimal("0");
		BigDecimal dayCommisionAmount = new BigDecimal("0");
		Set<String> orderDetailSet = new HashSet<>();
		
		if(list!=null&&list.size()>0){
			for(OrderSchedule sche:list){
				String statedateStr = DateUtil.date2Str(sche.getStatedate(), "yyyyMMdd");
				if(!orderDetailSet.contains(sche.getOrderDetailId())){
					orderDetailSet.add(sche.getOrderDetailId());
					monthAmount = monthAmount.add(sche.getBaseAmount());
					if(day.equals(statedateStr)){
						dayAmount = dayAmount.add(sche.getBaseAmount());
					}
				}
				if(sche.getCommisionAmount()!=null){
					monthCommisionAmount = monthCommisionAmount.add(sche.getCommisionAmount());
				}
				if(sche.getRoleId().equals(Constant.RoleIdEnum.FXS.toString())){
					fxsMonthAmount = fxsMonthAmount.add(sche.getBaseAmount());
				}
				if(day.equals(statedateStr)){
					if(sche.getCommisionAmount()!=null){
						dayCommisionAmount = dayCommisionAmount.add(sche.getCommisionAmount());
					}
				}
			}
			if(fxsMonthAmount.doubleValue()!=0){
				if(roleId.equals(Constant.RoleIdEnum.FXS.toString())){//发型师
					RoleCommisionRule rule = this.ruleService.getRatio(compId, fxsMonthAmount);
					BigDecimal ruleRatio = rule.getCommisionRatio().divide(new BigDecimal("100"));
					for(OrderSchedule sche:list){
						if(sche.getRoleId().equals(Constant.RoleIdEnum.FXS.toString())){
							BigDecimal amount = sche.getBaseAmount().multiply(ruleRatio);
							if("10A".equals(sche.getIsDk())){
								amount = amount.multiply(couponPercent);
							}
							if("10A".equals(sche.getIsBalance())){
								amount = amount.multiply(vipBalancePercent);
							}
							monthCommisionAmount = monthCommisionAmount.add(amount);

							if(day.equals(DateUtil.date2Str(sche.getStatedate(), "yyyyMMdd"))){
								dayCommisionAmount = dayCommisionAmount.add(amount);
							}
						}
					}
				}
			}
			monthAmount = monthAmount.setScale(1,BigDecimal.ROUND_HALF_UP);
			monthCommisionAmount = monthCommisionAmount.setScale(1,BigDecimal.ROUND_HALF_UP);
			dayAmount = dayAmount.setScale(1,BigDecimal.ROUND_HALF_UP);
			dayCommisionAmount = dayCommisionAmount.setScale(1,BigDecimal.ROUND_HALF_UP);
		}
		map.put("monthAmount", monthAmount);
		map.put("monthCommisionAmount", monthCommisionAmount);
		map.put("dayAmount", dayAmount);
		map.put("dayCommisionAmount", dayCommisionAmount);
		return map;
	}
	
	/**
	 * 获取员工业绩排行(不算商品)
	 * @param querier
	 * @return
	 */
	public List<OrderSchedule> getPerformanceRank(Querier querier){
		return this.getBaseMapper().selectPerformanceRank(querier);
	}
	
	/**
	 * 获取员工业绩明细
	 * @param querier
	 * @return
	 */
	public Map<String,List<PerformanceDetail>> getPerformanceDetail(String compId,String employeeId,String roleId,String dayType,String type){
		BigDecimal vipBalancePercent = new BigDecimal(sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.VIP_BALANCE_PERCENT.toString()).getVal1()).divide(new BigDecimal("100"));
		BigDecimal couponPercent = new BigDecimal(sysConfigService.getSysConfigMap().get(Constant.SysConfigItemEnum.COUPON_PERCENT.toString()).getVal1()).divide(new BigDecimal("100"));
		
		Date nowDate = new Date();
		String day = DateUtil.date2Str(nowDate, "yyyyMMdd");
		Querier querier = new Querier();
		querier.set("compId", compId);
		querier.set("employeeId", employeeId);
		if(roleId.equals(Constant.RoleIdEnum.FXS.toString())||dayType.equals("month")){//发型师
			querier.set("beginTime", DateUtil.getStartTime(DateUtil.getMonthFirstDate(nowDate, 0)));
			querier.set("endTime", DateUtil.getEndTime(nowDate));
		}else{
			querier.set("beginTime", DateUtil.getStartTime(nowDate));
			querier.set("endTime", DateUtil.getEndTime(nowDate));
		}
		
		querier.set("state", "10F");
		
		List<OrderSchedule> list = this.getBaseMapper().selectPerformanceDetail(querier);

		Map<String, List<PerformanceDetail>> map = new HashMap<>();
		Map<String, PerformanceDetail> serviceMap = new HashMap<String, PerformanceDetail>();
		Map<String, PerformanceDetail> mdseMap = new HashMap<String, PerformanceDetail>();

		BigDecimal fxsMonthAmount = new BigDecimal("0");
		Set<String> orderDetailSet = new HashSet<>();
		
		if(list!=null&&list.size()>0){
			BigDecimal ruleRatio = null;
			if(roleId.equals(Constant.RoleIdEnum.FXS.toString())){//发型师
				for(OrderSchedule sche:list){
					if(sche.getRoleId()!=null&&sche.getRoleId().equals(Constant.RoleIdEnum.FXS.toString())){
						fxsMonthAmount = fxsMonthAmount.add(sche.getBaseAmount());
					}
				}
				RoleCommisionRule rule = this.ruleService.getRatio(compId, fxsMonthAmount);
				ruleRatio = rule.getCommisionRatio().divide(new BigDecimal("100"));
			}

			for(OrderSchedule sche:list){
				if(dayType.equals("day")&&!day.equals(DateUtil.date2Str(sche.getStatedate(), "yyyyMMdd"))){
					continue;
				}
				if(sche.getRoleId()!=null){
					BigDecimal amount = sche.getCommisionAmount();
					if(sche.getRoleId().equals(Constant.RoleIdEnum.FXS.toString())){//发型师
						amount = sche.getBaseAmount().multiply(ruleRatio);
						if("10A".equals(sche.getIsDk())){
							amount = amount.multiply(couponPercent);
						}
						if("10A".equals(sche.getIsBalance())){
							amount = amount.multiply(vipBalancePercent);
						}
					}
					PerformanceDetail detail = serviceMap.get(sche.getMdseServiceName());
					if(detail==null){
						detail = new PerformanceDetail();
						detail.setMdseServiceName(sche.getMdseServiceName());
						detail.setMdseNum(sche.getMdseNum());
						if(type.equals("base")){
							detail.setPrice(sche.getBaseAmount());
						}else{
							detail.setPrice(amount);
						}
						orderDetailSet.add(sche.getOrderDetailId());
						serviceMap.put(sche.getMdseServiceName(), detail);
					}else{
						if(!orderDetailSet.contains(sche.getOrderDetailId())){
							orderDetailSet.add(sche.getOrderDetailId());
							detail.setMdseNum(detail.getMdseNum()+sche.getMdseNum());
						}
						if(type.equals("base")){
							detail.setPrice(detail.getPrice().add(sche.getBaseAmount()));
						}else{
							detail.setPrice(detail.getPrice().add(amount));
						}
					}
				}else{
					PerformanceDetail detail = mdseMap.get(sche.getMdseServiceName());
					if(detail==null){
						detail = new PerformanceDetail();
						detail.setMdseServiceName(sche.getMdseServiceName());
						detail.setMdseNum(sche.getMdseNum());
						if(type.equals("base")){
							detail.setPrice(sche.getBaseAmount());
						}else{
							detail.setPrice(sche.getCommisionAmount());
						}
						mdseMap.put(sche.getMdseServiceName(), detail);
					}else{
						detail.setMdseNum(detail.getMdseNum()+sche.getMdseNum());
						if(type.equals("base")){
							detail.setPrice(detail.getPrice().add(sche.getBaseAmount()));
						}else{
							detail.setPrice(detail.getPrice().add(sche.getCommisionAmount()));
						}
					}
				}
			}
		}
		map.put("service", new ArrayList<>(serviceMap.values()));
		map.put("mdse", new ArrayList<>(mdseMap.values()));
		return map;
	}
	
	public List<OrderSchedule> getUnServiceByEmployeeId(String employeeId){
		Date endDate = DateUtil.getDateBefore(new Date(), 7);
		return this.getBaseMapper().selectUnServiceByEmployeeId(employeeId, endDate);
	}
}
